package com.app.upgrader;

import android.content.Context;

import androidx.annotation.NonNull;

import com.zndroid.upgrader.downloader.IDownloadManager;
import com.zndroid.upgrader.listener.IDownloadListener;
import com.zndroid.upgrader.UpgraderX;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class MyDownManager implements IDownloadManager {
    private OkHttpDownUtil downUtil;
    private UpgraderX upgraderX;
    private IDownloadListener iDownloadListener;

    MyDownManager(Context context) {
        downUtil = new OkHttpDownUtil();
        upgraderX = UpgraderX.getInstance(context);
    }

    @Override
    public void startDownload(@NonNull String apkUrl, String apkName, final @NonNull IDownloadListener listener) {
        iDownloadListener = listener;
        iDownloadListener.start();
        downUtil.getRenewalDownRequest(apkUrl, new File(upgraderX.getDownloadPath() + "/haha.apk"), new HttpDownListener() {
            @Override
            public void onFailure(Call call, IOException e) {
                iDownloadListener.error(e);
            }

            @Override
            public void onResponse(Call call, Response response, long mTotalLength, long mAlreadyDownLength) {
                int curr = (int) (mAlreadyDownLength / (double) mTotalLength * 100.0);
                if (mTotalLength >= mAlreadyDownLength)
                    iDownloadListener.downloading(100, curr);
                if (mTotalLength == mAlreadyDownLength)
                    iDownloadListener.done(new File(upgraderX.getDownloadPath() + "/haha.apk"));
            }
        });
    }

    @Override
    public void stopDownload() {
        downUtil.destroy();
        iDownloadListener.cancel();
    }

    @Override
    public void pause() {
        downUtil.stop();
    }

    @Override
    public void continues() {
        downUtil.resume();
    }
}
